package net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Random;

import net.dto.ClientObject;
import net.dto.ServerObject;
import net.protocols.ServerProtocol;

public class NetworkConnection extends Thread implements Runnable{

	private ObjectOutputStream out;
	private ObjectInputStream in;
	private Socket client;
	private Server server;
	
	private int id;
	
	private ServerProtocol gprot;
	
	public NetworkConnection(int id, Socket client, Server server){
		this.id = id;
		this.client = client;
		this.server = server;
		this.gprot = new ServerProtocol(id);
		
		try {
			out = new ObjectOutputStream(client.getOutputStream());
			in = new ObjectInputStream(client.getInputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		ClientObject inputLine;
		ServerObject outputLine;
		try {
			outputLine = gprot.processInput(null);
			server.print("#Connection "+id+" > Initial message to client ("+id+"), "+outputLine);
			out.writeObject(outputLine);
		
			while ((inputLine = (ClientObject) in.readObject()) != null) {
				server.print("< Client "+id+" > "+inputLine);
			    outputLine = gprot.processInput(inputLine);
			    if(outputLine != null){
			    	server.print("#Connection "+id+" > "+outputLine);
			    	out.writeObject(outputLine);
			    }
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	public void startGame(){
		//StartGame
	}
	
	public void close(){
		try {
			in.close();
			out.close();
			client.close();	
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
